<template>
  <el-card>
    <el-form :rules="editMusicRules" :model="editMusicData" ref="editMusicRef" ::inline="true" status-icon>
      <el-row>
        <el-col :span="12">
          <el-form-item prop="songAddress" label="歌曲地址" label-width="80">
            <el-upload
                v-model:file-list="audioFileList"
                ref="audioUploadRef"
                :auto-upload="false"
                :action="audioUrl"
                :headers="header"
                show-file-list
                :limit="1"
                accept=".mp3,.wav,.flac,.m4a,.ogg"
                :before-upload="validateAudioFile"
                :on-exceed="audioFileHandleExceed"
                :on-error="audioFileUploadError"
                :on-success="audioFileUploadSuccess"
                list-type="text">
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button class="ml-3" type="success" @click="submitAudioUpload">
                上传文件至服务器
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  mp3/wav/flac 文件并且大小小于10MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="picAddress" label="歌曲图片地址" label-width="110">
            <el-upload
                v-model:file-list="picFileList"
                ref="picUploadRef"
                :auto-upload="false"
                :action="picUrl"
                :headers="header"
                show-file-list
                :limit="1"
                accept=".jpeg,.png,.jpg,.bmp"
                :before-upload="validatePicFile"
                :on-exceed="picFileHandleExceed"
                :on-error="picFileUploadError"
                :on-success="picFileUploadSuccess"
                list-type="picture">
              <template #trigger>
                <el-button type="primary">选择文件</el-button>
              </template>
              <el-button class="ml-3" type="success" @click="submitPicUpload">
                上传文件至服务器
              </el-button>
              <template #tip>
                <div class="el-upload__tip">
                  jpg/png/jpeg 文件并且大小小于3MB
                </div>
              </template>
            </el-upload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="songName" label="歌曲名" label-width="80">
            <el-input v-model="editMusicData.songName"
                      class="w-50 m-2"
                      placeholder="请输入歌曲名"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="singer" label="歌手名" label-width="110">
            <el-input v-model="editMusicData.singer"
                      class="w-50 m-2"
                      placeholder="请输入歌手名"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="作词" label-width="80">
            <el-input v-model="editMusicData.lyricist"
                      class="w-50 m-2"
                      placeholder="请输入作词人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="谱曲" label-width="110">
            <el-input v-model="editMusicData.composer"
                      class="w-50 m-2"
                      placeholder="请输入谱曲人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="编曲" label-width="80">
            <el-input v-model="editMusicData.arranger"
                      class="w-50 m-2"
                      placeholder="请输入谱曲人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="节奏" label-width="110">
            <el-input v-model="editMusicData.tempo"
                      class="w-50 m-2"
                      placeholder="请输入节拍人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="混音" label-width="80">
            <el-input v-model="editMusicData.remixer"
                      class="w-50 m-2"
                      placeholder="请输入混音人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="专辑" label-width="110">
            <el-input v-model="editMusicData.album"
                      class="w-50 m-2"
                      placeholder="请输入专辑"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="专辑艺人" label-width="80">
            <el-input v-model="editMusicData.albumArtist"
                      class="w-50 m-2"
                      placeholder="请输入专辑艺人"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="格式" label-width="110">
            <el-input v-model="editMusicData.format"
                      class="w-50 m-2"
                      placeholder="请输入制作格式"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item prop="songType" label="歌曲类型" label-width="80">
            <el-radio-group v-model="editMusicData.songType">
              <el-radio label="0">纯音乐</el-radio>
              <el-radio label="1">杂音乐</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="版权" label-width="110">
            <el-input v-model="editMusicData.copyright"
                      class="w-50 m-2"
                      placeholder="请输入版权"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="发行国家" label-width="80">
            <el-input v-model="editMusicData.releaseCountry"
                      class="w-50 m-2"
                      placeholder="请输入发行国家"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="发行日期" label-width="110">
            <el-date-picker v-model="editMusicData.releaseDate"
                            type="date"
                            class="w-50 m-2"
                            placeholder="请选择发行日期"
                            size="large"
                            autocomplete="off"
                            clearable validate-event>
            </el-date-picker>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col>
          <el-form-item label="歌词" label-width="80">
            <el-input v-model="editMusicData.lyric"
                      type="textarea"
                      :rows="15"
                      style="width: 1000px"
                      placeholder="请输入歌词"
                      size="large"
                      autocomplete="off"
                      clearable validate-event>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12" :offset="9">
          <el-form-item>
            <el-button type="primary" @click="submitEditMusic">提交</el-button>
            <el-button type="danger" @click="cancelEditMusic">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-card>
</template>

<script setup>
import { getCurrentInstance,onMounted, reactive, ref } from "vue";
import axios from "axios";
import {genFileId} from "element-plus";
const msg = getCurrentInstance().appContext.config.globalProperties.$message

const audioFileList=ref([{
  name: "",
  url: ""
}])

const picFileList=ref([{
  name:"",
  url:""
}]);

function fileList(editMusicDataValue,fileList,flag) {
  let index,ext;
  if(flag==="audio"){
    index=editMusicDataValue.songAddress.lastIndexOf(".")
    ext=editMusicDataValue.songAddress.substring(index+1);
    fileList.url=editMusicDataValue.songAddress;
  }else {
    index=editMusicDataValue.picAddress.lastIndexOf(".")
    ext=editMusicDataValue.picAddress.substring(index+1);
    fileList.url=editMusicDataValue.picAddress;
  }
  fileList.name=editMusicDataValue.songName+"."+ext;
}

//根据music的id查询music信息
function selectMusicSingleInfo(id){
  axios.get("/music/selectMusic/"+id).then(res => {
    let mg = res.data;
    if (mg.meta.code === 200) {
      editMusicData.value=mg.data;
      //上传音乐文件组件列表
      fileList(editMusicData.value,audioFileList.value[0],"audio");
      fileList(editMusicData.value,picFileList.value[0],"pic");
    } else {
      msg.error(mg.meta.msg);
    }
  }).catch(err => {
    //网络异常啥的
    msg.error(err);
  })
}

onMounted(()=>{
  //获取 音乐数据id
  let id=history.state.id;
  //获取路由传递的参数
  selectMusicSingleInfo(id);
})


let editMusicRef=ref();

//编辑音乐的数据
let editMusicData=ref({
  id:"",
  songName:"",
  singer:"",
  lyric:"",
  songType:"",
  picAddress:"",
  picRealAddress:"",
  songAddress:"",
  songRealAddress:"",
  totalTime:"",
  contentType:"",
  format:"",
  lyricist:"",
  composer:"",
  arranger:"",
  tempo:"",
  remixer:"",
  album:"",
  albumArtist:"",
  copyright:"",
  releaseDate:"",
  releaseCountry:""
});

const editMusicRules=reactive({
  songName:[
    {
      required:true,
      message: '歌名不能为空!',
      trigger: 'blur'
    }
  ],
  singer:[
    {
      required:true,
      message: '歌手名不能为空!',
      trigger: 'blur'
    }
  ],
  songType:[
    {
      required:true,
      message: '歌曲类型不能为空!',
      trigger: 'blur'
    }
  ],
  picAddress:[
    {
      required:true,
      message: '歌曲图片地址不能为空!',
      trigger: 'blur'
    }
  ],
  songAddress:[
    {
      required:true,
      message: '歌曲地址不能为空!',
      trigger: 'blur'
    }
  ]
})

//上传路径的头信息
let token = {
  "Authorization": sessionStorage.getItem('token')
}

let header=ref(token);

let picUrl=ref("http://127.0.0.1:8888/music/musicPicFileUpload");

let picUploadRef=ref();

//可以替换已经选择的文件
function picFileHandleExceed(files){
  picUploadRef.value.clearFiles();
  const file=files[0];
  file.uid=genFileId();
  picUploadRef.value.handleStart(file);
}

//图片文件上传前需要验证格式和大小
async function validatePicFile(file) {
  const fileTypes = ["image/jpeg", "image/png", "image/bmp"];
  if (fileTypes.indexOf(file.type) < 0) {
    msg.error("图片必须是jpeg,png,jpg,bmp等格式");
    return false;
  } else if (file.size / 1024 / 1024 > 3) {
    msg.error("音频文件过大,超出了限制的3MB大小");
    return false;
  }
  //文件上传前，判断真实地址是否有值，如果有值先删除之前上传的文件，否则直接上传
  let path = editMusicData.value.picRealAddress;
  if (path !== "" && path != null) {
    const options = {
      url: '/music/removeMusic',
      //这里数据应该也是可以简写的
      data: {
        realAddress: path
      },
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    };
    const res = await axios(options);
    let mg = res.data;
    return mg.meta.code === 200;
  }
  return true;
}

//图片文件上传成功！
//三个参数，response,file,fileList
function picFileUploadSuccess(response){
  let resObj=response.data;
  for (const resObjKey in resObj) {
    editMusicData.value[resObjKey]=resObj[resObjKey];
  }
  msg.success(response.meta.msg);
  //清空文件上传列表
  //picUploadRef.value.clearFiles();
}

//图片文件上传失败！
//三个参数，response,file,fileList
function picFileUploadError(response){
  msg.error(response.meta.msg);
}

//提交上传文件
function submitPicUpload(){
  picUploadRef.value.submit();
}

let audioUploadRef=ref();

let audioUrl=ref("http://127.0.0.1:8888/music/musicFileUpload");

//文件上传前验证文件的格式和大小
async function validateAudioFile(file){
  const fileTypes=["audio/mpeg","audio/wav","audio/flac","audio/x-m4a","audio/ogg"];
  if(fileTypes.indexOf(file.type)<0){
    msg.error("音频文件必须是mp3,wav,flac,m4a,ogg等格式");
    return false;
  }else if(file.size/1024/1024>10){
    msg.error("音频文件过大,超出了限制的10MB大小");
    return false;
  }
  //文件上传前，判断真实地址是否有值，如果有值先删除之前上传的文件，否则直接上传
  let path=editMusicData.value.songRealAddress;
  if(path!=="" && path!= null){
    const options = {
      url: '/music/removeMusic',
      //这里数据应该也是可以简写的
      data: {
        realAddress: path
      },
      method: 'POST',
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    };
    const res=await axios(options);
    let mg = res.data;
    return mg.meta.code === 200;
  }
  return true;
}

//对于单个音乐文件上传时，可以替换已经选择的文件
function audioFileHandleExceed(files){
  audioUploadRef.value.clearFiles();
  const file=files[0];
  file.uid=genFileId();
  audioUploadRef.value.handleStart(file);
}

//音频文件上传失败
function audioFileUploadError(response){
  msg.error(response.meta.msg);
}

//音频文件上传成功
function audioFileUploadSuccess(response){
  let resObj=response.data;
  for (const resObjKey in resObj) {
    editMusicData.value[resObjKey]=resObj[resObjKey];
  }
  msg.success(response.meta.msg);
}

//上传文件
function submitAudioUpload(){
  audioUploadRef.value.submit();
}

//取消编辑音乐数据
function cancelEditMusic(){
  //清空图片列表
  picUploadRef.value.clearFiles();
  //清空音乐列表
  audioUploadRef.value.clearFiles();
  //重置表单数据
  editMusicRef.value.resetFields();
  //重置editMusicData数据
  for (let property in editMusicData.value) {
    if(property==="songType"){
      editMusicData.value[property]="1";
    }else{
      editMusicData.value[property]="";
    }
  }
}

//提交编辑音乐数据
function submitEditMusic(){
  editMusicRef.value.validate(async validate => {
    if (!validate) return;
    const options = {
      //获取用户信息和权限信息
      url: '/music/updateMusic',
      data: editMusicData.value,
      method: 'PUT',
      headers: {'Content-Type': 'application/json'}
    };

    axios(options).then(res => {
      let mg = res.data;
      if (mg.meta.code === 200) {
        editMusicData.value=mg.data;
        //上传音乐文件组件列表
        fileList(editMusicData.value,audioFileList.value[0],"audio");
        fileList(editMusicData.value,picFileList.value[0],"pic");
        msg.success(mg.meta.msg);
      } else {
        msg.error(mg.meta.msg);
      }
    }).catch(err => {
      //网络异常啥的
      msg.error(err);
    })
  });
}
</script>

<style scoped>
  .el-input{
    width: 350px;
  }

  .ml-3{
    margin-left: 15px;
  }
</style>
